import 'package:flutter_test/flutter_test.dart';
import 'package:flutter/widgets.dart';
import 'package:native_video_cache/src/app_lifecycle_manager.dart';
import 'package:native_video_cache/src/cache_memory_manager.dart';
import 'package:native_video_cache/src/cache_stability_manager.dart';
import 'package:native_video_cache/src/cache_performance_monitor.dart';

void main() {
  group('管理器功能测试', () {
    setUp(() {
      WidgetsFlutterBinding.ensureInitialized();
    });

    tearDown(() {
      // 清理所有管理器
      AppLifecycleManager.instance.dispose();
      CacheMemoryManager.instance.dispose();
      CacheStabilityManager.instance.dispose();
      CachePerformanceMonitor.instance.dispose();
    });

    group('AppLifecycleManager 测试', () {
      test('单例模式测试', () {
        final instance1 = AppLifecycleManager.instance;
        final instance2 = AppLifecycleManager.instance;
        expect(instance1, equals(instance2));
      });

      test('初始化测试', () {
        final manager = AppLifecycleManager.instance;
        expect(manager.currentState, equals(AppLifecycleState.resumed));
        expect(manager.activeUrlCount, equals(0));

        manager.initialize();
        expect(manager.isInForeground, isTrue);
        expect(manager.isInBackground, isFalse);
      });

      test('URL注册测试', () {
        final manager = AppLifecycleManager.instance;
        manager.initialize();

        expect(manager.activeUrlCount, equals(0));

        manager.registerActiveUrl('test_url_1');
        expect(manager.activeUrlCount, equals(1));

        manager.registerActiveUrl('test_url_2');
        expect(manager.activeUrlCount, equals(2));

        manager.unregisterActiveUrl('test_url_1');
        expect(manager.activeUrlCount, equals(1));

        manager.dispose();
      });
    });

    group('CacheMemoryManager 测试', () {
      test('单例模式测试', () {
        final instance1 = CacheMemoryManager.instance;
        final instance2 = CacheMemoryManager.instance;
        expect(instance1, equals(instance2));
      });

      test('初始化和配置测试', () {
        final manager = CacheMemoryManager.instance;
        manager.initialize(maxUrls: 5, maxMemoryUsage: 1024 * 1024);

        final report = manager.getMemoryReport();
        expect(report['maxUrls'], equals(5));
        expect(report['maxMemoryUsage'], equals(1024 * 1024));
        expect(report['activeUrls'], equals(0));
        expect(report['memoryUsage'], equals(0));
      });

      test('URL状态管理测试', () {
        final manager = CacheMemoryManager.instance;
        manager.initialize(maxUrls: 3, maxMemoryUsage: 1024 * 1024);

        // 添加URL状态
        manager.addUrlState('url1', 'loading');
        manager.addUrlState('url2', 'completed');
        manager.addUrlState('url3', 'error');

        final report = manager.getMemoryReport();
        expect(report['activeUrls'], equals(3));

        // 测试LRU清理（添加第4个URL应该移除最旧的）
        manager.addUrlState('url4', 'loading');
        final reportAfterLRU = manager.getMemoryReport();
        expect(reportAfterLRU['activeUrls'], equals(3));
      });

      test('内存清理测试', () {
        final manager = CacheMemoryManager.instance;
        manager.initialize(maxUrls: 10, maxMemoryUsage: 1024);

        // 添加一些URL状态
        for (int i = 0; i < 5; i++) {
          manager.addUrlState('url$i', 'loading');
        }

        expect(manager.getMemoryReport()['activeUrls'], equals(5));

        manager.cleanup();

        // 清理后应该减少
        expect(manager.getMemoryReport()['activeUrls'], lessThan(5));
      });
    });

    group('CacheStabilityManager 测试', () {
      test('单例模式测试', () {
        final instance1 = CacheStabilityManager.instance;
        final instance2 = CacheStabilityManager.instance;
        expect(instance1, equals(instance2));
      });

      test('初始化测试', () async {
        final manager = CacheStabilityManager.instance;
        await manager.initialize();

        expect(manager.activeRetryCount, equals(0));
        expect(manager.failedRetryCount, equals(0));
        expect(manager.failedUrls, isEmpty);
      });

      test('重试上下文管理测试', () async {
        final manager = CacheStabilityManager.instance;
        await manager.initialize();

        // 注册缓存任务
        manager.registerCacheTask('test_url');
        expect(manager.activeRetryCount, equals(1));

        // 模拟失败
        manager.onCacheFailure('test_url', 'Network error');
        expect(manager.failedRetryCount, equals(1));
        expect(manager.failedUrls, contains('test_url'));

        // 模拟成功
        manager.registerCacheTask('success_url');
        manager.onCacheSuccess('success_url');
        expect(manager.activeRetryCount, equals(0));
      });

      test('稳定性统计测试', () async {
        final manager = CacheStabilityManager.instance;
        await manager.initialize();

        manager.registerCacheTask('url1');
        manager.registerCacheTask('url2');
        manager.onCacheFailure('url1', 'Error');

        final stats = manager.getStabilityStats();
        expect(stats['totalRetryContexts'], equals(2));
        expect(stats['activeRetries'], equals(1));
        expect(stats['failedRetries'], equals(1));
      });
    });

    group('CachePerformanceMonitor 测试', () {
      test('单例模式测试', () {
        final instance1 = CachePerformanceMonitor.instance;
        final instance2 = CachePerformanceMonitor.instance;
        expect(instance1, equals(instance2));
      });

      test('初始化测试', () {
        final monitor = CachePerformanceMonitor.instance;
        monitor.initialize();

        final report = monitor.getPerformanceReport();
        expect(report['totalUrls'], equals(0));
        expect(report['overallSuccessRate'], equals(0.0));
        expect(report['totalErrors'], equals(0));
      });

      test('性能事件记录测试', () {
        final monitor = CachePerformanceMonitor.instance;
        monitor.initialize();

        // 记录缓存开始
        monitor.recordCacheStart('test_url');

        // 记录进度更新
        monitor.recordProgressUpdate('test_url', 0.5);

        // 记录缓存完成
        monitor.recordCacheComplete('test_url');

        final report = monitor.getPerformanceReport();
        expect(report['totalUrls'], equals(1));
        expect(report['overallSuccessRate'], equals(1.0));

        final events = monitor.getRecentEvents();
        expect(events.length, greaterThan(0));
      });

      test('缓存指标测试', () {
        final monitor = CachePerformanceMonitor.instance;
        monitor.initialize();

        monitor.recordCacheStart('test_url');
        monitor.recordProgressUpdate('test_url', 0.8);
        monitor.recordCacheComplete('test_url');

        final metrics = monitor.getUrlMetrics('test_url');
        expect(metrics, isNotNull);
        expect(metrics!.url, equals('test_url'));
        expect(metrics.successCount, equals(1));
        expect(metrics.successRate, equals(1.0));
      });

      test('失败处理测试', () {
        final monitor = CachePerformanceMonitor.instance;
        monitor.initialize();

        monitor.recordCacheStart('fail_url');
        monitor.recordCacheFailure('fail_url', 'Network timeout');

        final report = monitor.getPerformanceReport();
        expect(report['totalUrls'], equals(1));
        expect(report['overallSuccessRate'], equals(0.0));
        expect(report['totalErrors'], equals(1));

        final topErrors = report['topErrors'] as List;
        expect(topErrors.isNotEmpty, isTrue);
      });

      test('内存使用记录测试', () {
        final monitor = CachePerformanceMonitor.instance;
        monitor.initialize();

        monitor.recordMemoryUsage(10, 5);

        final events = monitor.getRecentEvents();
        final memoryEvent = events.firstWhere(
          (event) => event.type.toString().contains('memoryUsage'),
          orElse: () => throw Exception('Memory event not found'),
        );

        expect(memoryEvent.data!['totalListeners'], equals(10));
        expect(memoryEvent.data!['cacheStates'], equals(5));
      });
    });

    group('管理器集成测试', () {
      test('多管理器协同工作测试', () async {
        // 初始化所有管理器
        AppLifecycleManager.instance.initialize();
        CacheMemoryManager.instance
            .initialize(maxUrls: 10, maxMemoryUsage: 1024 * 1024);
        await CacheStabilityManager.instance.initialize();
        CachePerformanceMonitor.instance.initialize();

        final testUrl = 'test_integration_url';

        // 模拟缓存流程
        AppLifecycleManager.instance.registerActiveUrl(testUrl);
        CacheMemoryManager.instance.addUrlState(testUrl, 'loading');
        CacheStabilityManager.instance.registerCacheTask(testUrl);
        CachePerformanceMonitor.instance.recordCacheStart(testUrl);

        // 验证各管理器状态
        expect(AppLifecycleManager.instance.activeUrlCount, equals(1));
        expect(CacheMemoryManager.instance.getMemoryReport()['activeUrls'],
            equals(1));
        expect(CacheStabilityManager.instance.activeRetryCount, equals(1));

        final performanceReport =
            CachePerformanceMonitor.instance.getPerformanceReport();
        expect(performanceReport['totalUrls'], equals(1));

        // 模拟成功完成
        CachePerformanceMonitor.instance.recordCacheComplete(testUrl);
        CacheStabilityManager.instance.onCacheSuccess(testUrl);
        CacheMemoryManager.instance.updateUrlState(testUrl, 'completed');
        AppLifecycleManager.instance.unregisterActiveUrl(testUrl);

        // 验证清理状态
        expect(AppLifecycleManager.instance.activeUrlCount, equals(0));
        expect(CacheStabilityManager.instance.activeRetryCount, equals(0));

        final finalReport =
            CachePerformanceMonitor.instance.getPerformanceReport();
        expect(finalReport['overallSuccessRate'], equals(1.0));
      });
    });
  });
}
